import time

import cv2 as cv


class Camera:
    __cap = None
    isOpen = False

    def open_camera(self):
        if self.__cap is None:
            self.__cap = cv.VideoCapture(0)
            self.isOpen = self.__cap.isOpened
            return self.isOpen

    def gather_camera_img(self):
        if self.isOpen is False:
            self.open_camera()
        while self.isOpen:
            ret, frame = self.__cap.read()
            if not ret:
                break
            ret1, buffer = cv.imencode('.jpg', frame)
            picBytes = buffer.tobytes()
            time.sleep(0.016)
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + picBytes + b'\r\n')

    def close_camera(self):
        self.__cap.release()
        self.__cap = None
        self.isOpen = False
